<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="cardType">
        <el-select
          v-model="queryParams.cardType"
          clearable
          filterable
          placeholder="请选来源"
          style="width: 100%"
        >
          <el-option :key="1" label="周卡" value="周卡" />
          <el-option :key="1" label="月卡" value="月卡" />
          <el-option :key="1" label="季卡" value="季卡" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['phoneBill:receive:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['phoneBill:receive:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['phoneBill:receive:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['phoneBill:receive:import']"
          >导入</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['phoneBill:receive:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="创建时间"
        align="center"
        key="createTime"
        prop="createTime"
        v-if="columns[0].visible"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="权益名称"
        align="center"
        key="equityName"
        prop="equityName"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="权益编号"
        align="center"
        key="equityCode"
        prop="equityCode"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="权益类型"
        align="center"
        key="cardType"
        prop="cardType"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="展示价格"
        align="center"
        key="var1"
        prop="var1"
        v-if="columns[4].visible"
        width="120"
      />
      <el-table-column
        label="来源"
        align="center"
        key="source"
        prop="source"
        v-if="columns[5].visible"
        width="120"
      >
        <template #default="scope">
          <span v-if="scope.row.source == 1">新芽</span>
          <span v-if="scope.row.source == 2">聚充</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        key="remark"
        prop="remark"
        v-if="columns[6].visible"
        width="120"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:code:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        :model="form.info"
        :rules="rules"
        ref="userRef"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="权益名称" prop="equityName">
              <el-input v-model="form.info.equityName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="权益编码" prop="equityCode">
              <el-input v-model="form.info.equityCode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="展示价格" prop="var1">
              <el-input v-model="form.info.var1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="来源" prop="source">
              <el-select
                v-model="form.info.source"
                clearable
                filterable
                placeholder="请选来源"
                style="width: 100%"
              >
                <el-option :key="1" label="新芽" :value="1" />
                <el-option :key="1" label="聚充" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型" prop="cardType">
              <el-select
                v-model="form.info.cardType"
                clearable
                filterable
                placeholder="请选来源"
                style="width: 100%"
              >
                <el-option :key="1" label="周卡" value="周卡" />
                <el-option :key="1" label="月卡" value="月卡" />
                <el-option :key="1" label="季卡" value="季卡" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.info.remark" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="权益图" prop="file">
              <el-upload
                list-type="picture-card"
                ref="uploadRef"
                :limit="1"
                :file-list="fileList"
                :show-file-list="true"
                :headers="upload.headers"
                :action="upload.url"
                accept="image/*"
                :on-success="handleFileSuccess"
                :on-change="handleChageImg1"
                :auto-upload="true"
              >
                <el-icon><Plus /></el-icon>

                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>

              <el-dialog v-model="dialogVisible" width="50%">
                <img :src="dialogImageUrl" alt="Preview Image" class="img" />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button @click="createEquity" type="primary">确 定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import {
  listEquity,
  addEquity,
  editEquity,
  delEquity,
} from "@/api/member/list";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  //上传地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/equityCard/avatar",
});

// 列显隐信息
const columns = ref([
  { key: 0, label: `创建时间`, visible: true },
  { key: 1, label: `权益名称`, visible: true },
  { key: 2, label: `权益编号`, visible: true },
  { key: 3, label: `权益类型`, visible: true },
  { key: 4, label: `展示价格`, visible: true },
  { key: 5, label: `来源`, visible: true },
  { key: 6, label: `备注`, visible: true },
]);

const data = reactive({
  form: { info: {} },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phoneNumber: undefined,
    cardType: undefined,
  },
  rules: {
    equityName: [
      { required: true, message: "权益名称名称不能为空", trigger: "blur" },
    ],
    equityCode: [
      { required: true, message: "权益编码不能为空", trigger: "blur" },
    ],
    var1: [{ required: true, message: "展示价格不能为空", trigger: "blur" }],
    source: [{ required: true, message: "来源不能为空", trigger: "blur" }],
    cardType: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listEquity(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      userList.value = res.rows;
      total.value = res.total;
    }
  );
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  // proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}
const fileList = ref([]); /**图片列表 */
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

/** 重置操作表单 */
function reset() {
  form.value.info = {};
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 添加 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}

const handleChageImg1 = (file, resfileList) => {
  const size = ref(5);
  const fileSizeFlag = file.size / 1024 / 1024 < size.value;
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`);
    fileList.value = [];
  } else {
    fileList.value = resfileList;
  }
};

const handleRemove = (file) => {
  proxy.$refs["uploadRef"].handleRemove(file);
  form.value.info.imagePath = "";
  console.log(file);
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
const handleFileSuccess = (response, file, fileList) => {
  // console.log(response, "09211as");
  form.value.info.imagePath = response.msg;
};

//修改
const baseUrl = "https://fx.yunyoutongxin.com/prod-api";

function handleUpdate(row) {
  reset();
  form.value.info = row;
  title.value = "修改";
  open.value = true;
  if (row.imagePath) {
    fileList.value = row.imagePath?.split(",").map((item) => {
      return {
        url: `${baseUrl}${item}`,
      };
    });
  }
}

//提交
const submit = async () => {
  await proxy.$refs["uploadRef"].submit();
  if (title.value === "新增") {
    await addEquity(form.value.info).then((res) => {
      if (res.code == 200) {
        open.value = false;
        getList();
      }
      proxy.$modal.msgSuccess(res.msg);
    });
  } else {
    await editEquity(form.value.info).then((res) => {
      if (res.code == 200) {
        open.value = false;
        getList();
      }
      proxy.$modal.msgSuccess(res.msg);
    });
  }
};
const createEquity = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      submit();
    }
  });
};

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return delEquity(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download(
//     "system/equityReceive/export",
//     {
//       ...queryParams.value,
//     },
//     `会员权益领取记录${new Date().getTime()}.xlsx`
//   );
// }

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

getList();
</script>
<style lang="scss" scoped>
.img {
  width: 100%;
  height: 100%;
}
</style>
